# -*- coding: utf-8 -*-
# created on 2017/01/20

from sympy import sympify
from mathsolver.functions.base import BaseExpression
from mathsolver.functions.base import BaseFunction, BaseNumber
from mathsolver.functions.hanshu.helper import check_inter, reverse_zuizhi
from mathsolver.functions.sympy_utils import get_all_child


def is_symmetric_interval(inter1, inter2):
    """判断区间是否对称"""
    return (inter1._sup, inter1._inf) == (-inter2._inf, -inter2._sup)


class JiOuDuiChengZuiZhi(BaseFunction):
    """hs105.奇函数的对称性求函数最值，
        hs106.偶函数的对称性求函数最值"""

    def solver(self, *args):
        # 输入
        jiou, fx1, inter1, zuizhi, number, fx2, inter2 = args
        inter1 = check_inter(inter1)
        inter2 = check_inter(inter2)

        assert fx1.value == fx2.value and is_symmetric_interval(inter1, inter2)

        if "奇" in jiou:
            res = BaseNumber(-number.sympify())
            self.steps.append(["", "奇函数在对称区间的最值性相反，最值互为相反数"])
        else:
            res = number
            self.steps.append(["", "偶函数在对称区间的最值性相同，最值相同"])

        self.steps.append(["", "所以 %s 在 %s 上有 %s %s" % (fx2.printing(), inter2, reverse_zuizhi(zuizhi), res.value)])

        self.output.append(res)
        self.label.add("函数的奇偶性和对称性求最值")
        return self


class JiHanShuDuiChengZuiZhi(BaseFunction):
    """062.函数奇偶性的对称性求最值"""

    def solver(self, *args):
        funceq, inter1, zuizhi, number, func_q, inter2 = args
        funceq_left, funceq_right = sympify(funceq.value)
        assert is_symmetric_interval(inter1, inter2)

        # f(x) = g(x) + m, 假设能证明 g(x) 是奇函数
        m = get_all_child(funceq_right, lambda x: x.is_Atom)[0]
        funceq_right_rest = funceq_right - m
        M = number.sympify()

        self.steps.append(["", "由题意可知 %s 为奇函数" % funceq_right_rest])
        self.steps.append(["", "%s 的%s为%s" % (funceq_right_rest, zuizhi, M - m)])
        self.steps.append(["%s 与 %s 互为对称区间" % (inter1, inter2),
                           "所以 %s 的%s为 %s" % (funceq_right_rest, reverse_zuizhi(zuizhi), m - M)])
        self.steps.append(["", "所以 %s 在 %s 上有%s为%s" %
                           (func_q.printing(), inter2, reverse_zuizhi(zuizhi), 2 * m - M)])

        self.output.append(BaseExpression(reverse_zuizhi(zuizhi)))
        self.output.append(BaseNumber(2 * m - M))
        self.label.add("函数奇偶性的对称性求最值")
        return self


if __name__ == '__main__':
    pass
